import axios from 'axios'
import router from '@/router'
import { Loading, Message } from 'element-ui'
import { requestApi } from '@/requset/api'
var dayjs = require('dayjs')
var loadingNum = 0
let errorText = true
var loading
let message = false
export function startLoading() {
    loading = Loading.service({
        target: 'body',
        background: 'rgb(0,0,0,.4)',
    })
}
//结束加载动画
export function endLoading() {
    loading.close()
}
const instance = axios.create({
    baseURL: '/api',
    timeout: 500000,
})
instance.interceptors.request.use((config) => {
    let token = localStorage.getItem('token')
    config.headers['Content-Type'] = 'application/json'
    if (token) {
        config.headers['Authorization'] = localStorage.getItem('token')
    }
    if (config.headers.isLoading) {
        loadingNum++ //记录需要加载动画的接口数量
        startLoading() //请求时的加载动画
    }
    return config
})

instance.interceptors.response.use(
    (res) => {
        // token异常
        if (res.data.code == -1000) {
            if (errorText) {
                if (!message) {
                    errorText = false
                    localStorage.removeItem('token')

                    return new Promise((resolve, reject) => {
                        loadingNum = 0 //遇到一个报错 则所有的动画都结束
                        endLoading()
                        Message.info('登录状态过期')
                        reject()
                        router.push('/')
                        errorText = true
                        message = true
                        setTimeout(() => {
                            message = false
                        }, 5000)
                        return
                    })
                }
            }
        }
        if (res.config.headers.isLoading) {
            loadingNum--
            if (loadingNum == 0) {
                endLoading() //结束加载动画
            }
        }
        return res
    },
    (err) => {
        if (err.code === 'ECONNABORTED' && err.config.url !== 'mqtt/getlist' && !err.config.url.includes('openapi')) {
            console.log('请求超时！')
            requestApi('post', 'log/add', {
                title: err.message,
                type: 'AxiosError',
                url: err.config.url,
                user_name: sessionStorage.getItem('user_name'),
                content: '',
                create_time: dayjs().format('YYYY-MM-DD HH:mm:ss'),
            }).then()
            if (!message) {
                Message.error('网络异常，请稍后重试')
                message = true
                setTimeout(() => {
                    message = false
                }, 5000)
            }
        } else {
            console.log('请求出错！')
        }
        loadingNum = 0 //遇到一个报错 则所有的动画都结束
        endLoading()
        return Promise.reject(err)
    },
)
export default instance
